<template>
  <view class="container" :style="appThemeStyle">
    <!-- 搜索头部 -->
    <view class="search-header">
      <view class="search-wrapper">
        <view class="search-input">
          <view class="search-input-wrapper">
            <view class="left">
              <text class="search-icon">🔍</text>
            </view>
            <view class="right">
              <input 
                v-model="searchValue" 
                class="input" 
                placeholder="请输入您搜索的企业" 
                type="text"
                @input="onSearchInput"
                @confirm="onSearch"
              />
            </view>
          </view>
        </view>
        <view class="search-button">
          <view class="button" @click="onSearch">搜索</view>
        </view>
      </view>
    </view>

    <!-- 列表内容 -->
    <mescroll-body 
      ref="mescrollRef" 
      :sticky="true" 
      @init="mescrollInit" 
      :down="{ use: false }" 
      :up="upOption" 
      :bottombar="false"
      @up="upCallback"
    >
      <!-- 筛选区域 -->
      <view class="filter-section">
        <view class="filter-row">
          <view class="filter-item">
            <text class="filter-label">纳税等级</text>
            <picker 
              class="filter-picker"
              :value="taxLevelSelectedIndex"
              :range="taxLevelOptions"
              range-key="name"
              @change="onTaxLevelChange"
            >
              <view class="picker-display">
                <text class="picker-text">
                  {{ taxLevelOptions[taxLevelSelectedIndex]?.name || '全部等级' }}
                </text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
          </view>
          
          <view class="filter-item">
            <text class="filter-label">企业状况</text>
            <picker 
              class="filter-picker"
              :value="companyStatusSelectedIndex"
              :range="companyStatusOptions"
              range-key="name"
              @change="onCompanyStatusChange"
            >
              <view class="picker-display">
                <text class="picker-text">
                  {{ companyStatusOptions[companyStatusSelectedIndex]?.name || '全部状况' }}
                </text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
          </view>
          
          <view class="filter-reset" @click="resetFilters">
            <text class="reset-text">重置</text>
          </view>
        </view>
      </view>
      <view class="list-content">
        <!-- 企业列表 -->
        <view class="company-list">
          <view 
            class="company-item" 
            v-for="(item, index) in goodsList.data" 
            :key="index"
            @click="onTargetCompany(item)"
          >
            <view class="company-info">
              <!-- 企业名称和业务范围 -->
              <view class="company-details">
                <text class="company-name">{{ item.goods_name || item.company_name || item.name }}</text>
                <view class="business-scope" v-if="item.business_scope">
                  <text class="scope-text">{{ item.business_scope }}</text>
                </view>
              </view>
              
              <!-- 资质标签 -->
              <view class="company-tags">
                <text 
                  class="tag" 
                  :class="getQualificationTagClass(qualification)"
                  v-for="(qualification, qIndex) in parseQualificationStatus(item.qualification_status)" 
                  :key="qIndex"
                >
                  <view class="tag-icon" :class="getQualificationIconClass(qualification)"></view>
                  {{ qualification }}
                </text>
                <!-- 如果没有资质信息，显示默认标签 -->
                <text class="tag" v-if="!item.qualification_status">
                  <view class="tag-icon icon-office"></view>
                  法人服务
                </text>
              </view>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="goodsList.data.length === 0 && !loading" class="empty-state">
          <view class="empty-icon icon-document"></view>
          <text class="empty-text">{{ searchValue ? `暂无"${searchValue}"相关企业信息` : '暂无企业信息' }}</text>
        </view>
      </view>
    </mescroll-body>
  </view>
</template>

<script>
import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins'
import { getEmptyPaginateObj, getMoreListData } from '@/core/app'
import * as GoodsApi from '@/api/goods'

const pageSize = 15

export default {
  mixins: [MescrollMixin],
  props: {
    list: {
      type: Array,
      default: []
    },
    setting: {
      type: Object,
      default: () => {}
    },
  },
  data() {
    return {
      // 搜索关键词
      searchValue: '',
      // 搜索防抖定时器
      searchTimer: null,
      // 企业列表
      goodsList: getEmptyPaginateObj(),
      // 加载状态
      loading: false,
      // 筛选条件
      selectedTaxLevel: '', // 纳税等级筛选值
      selectedCompanyStatus: '', // 企业状况筛选值
      taxLevelSelectedIndex: 0, // 纳税等级选中索引
      companyStatusSelectedIndex: 0, // 企业状况选中索引
      // 纳税等级选项
      taxLevelOptions: [
        { value: '', name: '全部等级' },
        { value: '10', name: 'A级' },
        { value: '20', name: 'B级' },
        { value: '30', name: 'C级' }
      ],
      // 企业状况选项
      companyStatusOptions: [
        { value: '', name: '全部状况' },
        { value: '10', name: '企业状态良好' },
        { value: '20', name: '企业状态一般' },
        { value: '30', name: '企业状态不佳' }
      ],
      // 上拉加载配置
      upOption: {
        auto: true, // 默认自动加载
        page: { size: pageSize },
        noMoreSize: 3,
        toTop: { right: 30, bottom: 48, zIndex: 9 }
      }
    }
  },
  methods: {
    /**
     * 纳税等级筛选变化
     */
    onTaxLevelChange(e) {
      this.taxLevelSelectedIndex = e.detail.value
      this.selectedTaxLevel = this.taxLevelOptions[e.detail.value].value
      this.onRefreshList() // 重新调用接口
    },

    /**
     * 企业状况筛选变化
     */
    onCompanyStatusChange(e) {
      this.companyStatusSelectedIndex = e.detail.value
      this.selectedCompanyStatus = this.companyStatusOptions[e.detail.value].value
      this.onRefreshList() // 重新调用接口
    },

    /**
     * 重置筛选条件
     */
    resetFilters() {
      this.selectedTaxLevel = ''
      this.selectedCompanyStatus = ''
      this.taxLevelSelectedIndex = 0
      this.companyStatusSelectedIndex = 0
      this.onRefreshList() // 重新调用接口
    },

    /**
     * 上拉加载的回调
     */
    upCallback(page) {
      const app = this
      app.getGoodsList(page.num)
        .then(list => {
          const curPageLen = list.data.length
          const totalSize = list.data.total
          app.mescroll.endBySize(curPageLen, totalSize)
        })
        .catch(() => app.mescroll.endErr())
    },

    /**
     * 获取企业列表 - 传递所有筛选参数给后端
     */
    getGoodsList(pageNo = 1) {
      const app = this
      return new Promise((resolve, reject) => {
        const param = {
          sortType: 'all',
          sortPrice: 0,
          categoryId: 0,
          goodsName: app.searchValue || '', // 搜索关键词
          tax_brackets: app.selectedTaxLevel || '', // 纳税等级
          enterprise_status: app.selectedCompanyStatus || '', // 企业状况
          page: pageNo,
          filters: [],
          onlyInStock: false
        }
        
        GoodsApi.list(param)
          .then(result => {
            const newList = result.data.list
            app.goodsList.data = getMoreListData(newList, app.goodsList, pageNo)
            app.goodsList.last_page = newList.last_page
            resolve(newList)
          })
          .catch(reject)
      })
    },

    /**
     * 搜索输入事件
     */
    onSearchInput(e) {
      const app = this
      const value = e.detail.value || e.target.value
      app.searchValue = value
      
      // 防抖处理
      if (app.searchTimer) {
        clearTimeout(app.searchTimer)
      }
      
      app.searchTimer = setTimeout(() => {
        app.onRefreshList() // 重新调用接口
      }, 500)
    },

    /**
     * 执行搜索
     */
    onSearch() {
      this.onRefreshList() // 重新调用接口
    },

    /**
     * 刷新列表数据
     */
    onRefreshList() {
      this.goodsList = getEmptyPaginateObj()
      setTimeout(() => {
        if (this.mescroll) {
          this.mescroll.resetUpScroll()
        }
      }, 120)
    },

    /**
     * 点击企业项
     */
    onTargetCompany(item) {
      console.log('点击企业:', item)
      const goodsId = item.goods_id || item.company_id || item.id
      this.$navTo('pages/goods/detail', { goodsId })
    },

    /**
     * 解析资质状态，返回对应的资质名称数组
     */
    parseQualificationStatus(qualificationStatus) {
      if (!qualificationStatus) return []
      
      // 现在直接返回文字，按逗号分割即可
      return qualificationStatus.split(',')
        .map(status => status.trim())
        .filter(status => status) // 过滤空字符串
    },

    /**
     * 获取资质对应的图标 class
     */
    getQualificationIconClass(qualification) {
      const classMap = {
        'ISO9001': 'icon-medal',
        'ISO9901': 'icon-medal', // 兼容可能的拼写
        '高新技术企业': 'icon-lightning', 
        '涉密资质': 'icon-lock'
      }
      return classMap[qualification] || 'icon-tag'
    },

    /**
     * 获取资质对应的标签样式 class
     */
    getQualificationTagClass(qualification) {
      const classMap = {
        'ISO9001': 'tag-orange',      // 橙色
        'ISO9901': 'tag-orange',      // 兼容可能的拼写
        '高新技术企业': 'tag-green',   // 绿色
        '涉密资质': 'tag-blue'        // 蓝色
      }
      return classMap[qualification] || ''
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  background: #f7f7f7;
  min-height: 100vh;
}

// 搜索头部
.search-header {
  position: fixed;
  top: var(--window-top);
  left: var(--window-left);
  right: var(--window-right);
  z-index: 100;
  background: #fff;
  padding: 24rpx 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
  border-bottom: 1rpx solid #f0f0f0;
}

.search-wrapper {
  display: flex;
  height: 64rpx;
}

// 搜索输入框
.search-input {
  flex: 1;
  background: #f8f9fa;
  border-radius: 12rpx 0 0 12rpx;
  border: 1rpx solid #e9ecef;
  box-sizing: border-box;
  overflow: hidden;
}

.search-input-wrapper {
  display: flex;

  .left {
    display: flex;
    width: 60rpx;
    justify-content: center;
    align-items: center;

    .search-icon {
      display: block;
      color: #b4b4b4;
      font-size: 28rpx;
    }
  }

  .right {
    flex: 1;

    .input {
      font-size: 28rpx;
      height: 64rpx;
      display: flex;
      align-items: center;
      width: 100%;
      padding: 0;
      border: none;
      outline: none;
      background: transparent;
    }
  }
}

// 搜索按钮
.search-button {
  width: 120rpx;
  box-sizing: border-box;

  .button {
    height: 64rpx;
    font-size: 28rpx;
    border-radius: 0 12rpx 12rpx 0;
    background: #409eff;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: 500;
  }
}

// 列表内容
.list-content {
  background: #fff;
  min-height: 100vh;
}

// 企业列表
.company-list {
  background: #fff;
}

.company-item {
  padding: 32rpx 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
  display: flex;
  align-items: flex-start;
  
  &:last-child {
    border-bottom: none;
  }
  
  &:active {
    background: #f8f9fa;
  }
}

.company-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

// 企业头部信息
.company-details {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.company-name {
  font-size: 32rpx;
  color: #303133;
  line-height: 1.5;
  font-weight: 600;
  margin-bottom: 4rpx;
}

// 业务范围
.business-scope {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.scope-text {
  font-size: 26rpx;
  color: #909399;
  line-height: 1.4;
}

// 资质标签 - 完全模仿 Element UI Tag 组件
.company-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-top: 4rpx;
}

.tag {
  display: inline-flex;
  align-items: center;
  height: 36rpx;
  padding: 0 16rpx;
  font-size: 22rpx;
  line-height: 34rpx;
  border: 1rpx solid #d9ecff;
  border-radius: 6rpx;
  box-sizing: border-box;
  white-space: nowrap;
  background-color: #ecf5ff;
  color: #409eff;
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
  font-weight: 400;
}

// 橙色标签 (ISO9001)
.tag-orange {
  border: 1rpx solid #ffd591;
  background-color: #fff7e6;
  color: #fa8c16;
}

// 绿色标签 (高新技术企业)
.tag-green {
  border: 1rpx solid #b7eb8f;
  background-color: #f6ffed;
  color: #52c41a;
}

// 蓝色标签 (涉密资质)
.tag-blue {
  border: 1rpx solid #91d5ff;
  background-color: #e6f7ff;
  color: #1890ff;
}

// CSS 绘制的图标 - Element Plus 风格
.tag-icon {
  width: 16rpx;
  height: 16rpx;
  margin-right: 8rpx;
  display: inline-block;
  position: relative;
}

// 奖章图标 (ISO9001)
.icon-medal {
  background: #409eff;
  border-radius: 50%;
  
  &::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 8rpx;
    height: 8rpx;
    background: #fff;
    border-radius: 50%;
  }
}

// 橙色标签中的奖章图标
.tag-orange .icon-medal {
  background: #fa8c16;
}

// 闪电图标 (高新技术企业)
.icon-lightning {
  background: linear-gradient(45deg, transparent 40%, #409eff 40%, #409eff 60%, transparent 60%);
  transform: skew(-10deg);
}

// 绿色标签中的闪电图标
.tag-green .icon-lightning {
  background: linear-gradient(45deg, transparent 40%, #52c41a 40%, #52c41a 60%, transparent 60%);
}

// 锁图标 (涉密资质)
.icon-lock {
  background: #409eff;
  border-radius: 2rpx;
  
  &::before {
    content: '';
    position: absolute;
    top: -4rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 10rpx;
    height: 8rpx;
    border: 2rpx solid #409eff;
    border-bottom: none;
    border-radius: 6rpx 6rpx 0 0;
    background: transparent;
  }
}

// 蓝色标签中的锁图标
.tag-blue .icon-lock {
  background: #1890ff;
  
  &::before {
    border-color: #1890ff;
  }
}

// 标签图标 (默认)
.icon-tag {
  background: #409eff;
  border-radius: 2rpx 8rpx 8rpx 2rpx;
  
  &::before {
    content: '';
    position: absolute;
    left: -4rpx;
    top: 50%;
    transform: translateY(-50%);
    width: 0;
    height: 0;
    border-top: 8rpx solid transparent;
    border-bottom: 8rpx solid transparent;
    border-right: 4rpx solid #409eff;
  }
}

// 办公楼图标 (法人服务)
.icon-office {
  background: #409eff;
  border-radius: 2rpx;
  
  &::before {
    content: '';
    position: absolute;
    top: 2rpx;
    left: 2rpx;
    right: 2rpx;
    bottom: 2rpx;
    background: repeating-linear-gradient(
      0deg,
      transparent,
      transparent 2rpx,
      #fff 2rpx,
      #fff 3rpx
    );
  }
}

// 文档图标 (空状态)
.icon-document {
  width: 60rpx;
  height: 60rpx;
  background: #409eff;
  border-radius: 4rpx;
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 8rpx;
    left: 8rpx;
    right: 8rpx;
    bottom: 8rpx;
    background: repeating-linear-gradient(
      0deg,
      transparent,
      transparent 4rpx,
      #fff 4rpx,
      #fff 6rpx
    );
  }
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 120rpx 0;
  gap: 24rpx;
}

.empty-icon {
  opacity: 0.4;
}

.empty-text {
  font-size: 28rpx;
  color: #909399;
  text-align: center;
}

// 筛选区域
.filter-section {
  background: #fff;
  padding: 20rpx 24rpx;
  margin-top: 80px;
  border-bottom: 1rpx solid #f0f0f0;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 16rpx;
  flex-wrap: nowrap;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
  flex-shrink: 0;
}

.filter-label {
  font-size: 24rpx;
  color: #606266;
  white-space: nowrap;
  flex-shrink: 0;
}

.filter-picker {
  min-width: 120rpx;
  max-width: 140rpx;
}

.picker-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8rpx 12rpx;
  background: #f8f9fa;
  border: 1rpx solid #e9ecef;
  border-radius: 6rpx;
  min-width: 120rpx;
  max-width: 140rpx;
}

.picker-text {
  font-size: 24rpx;
  color: #303133;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.picker-arrow {
  font-size: 18rpx;
  color: #909399;
  margin-left: 6rpx;
  flex-shrink: 0;
}

.filter-reset {
  margin-left: auto;
  padding: 8rpx 16rpx;
  background: #f56c6c;
  border-radius: 6rpx;
  flex-shrink: 0;
}

.reset-text {
  font-size: 22rpx;
  color: #fff;
  white-space: nowrap;
}

// 响应式适配
@media screen and (max-width: 750rpx) {
  .filter-section {
    padding: 16rpx 20rpx;
  }
  
  .filter-row {
    gap: 12rpx;
  }
  
  .filter-item {
    gap: 6rpx;
  }
  
  .filter-label {
    font-size: 22rpx;
  }
  
  .filter-picker {
    min-width: 100rpx;
    max-width: 120rpx;
  }
  
  .picker-display {
    padding: 6rpx 10rpx;
    min-width: 100rpx;
    max-width: 120rpx;
  }
  
  .picker-text {
    font-size: 22rpx;
  }
  
  .filter-reset {
    padding: 6rpx 12rpx;
  }
  
  .reset-text {
    font-size: 20rpx;
  }
}
</style>
